from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError

# Create your models here.
def positiveOrZero(number):
    if number < 0:
        raise ValidationError("Number is negative")
 
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    
class Account(models.Model):
    ACCOUNT_CHOICES = (
       (u'sa', u'Savings account'),
       (u'se', u'Service account'),
       (u'ia', u'Investment account'),
       (u'la', u'Loans account'),
    )
    number = models.CharField(max_length=18, unique=True)
    user = models.ForeignKey(User)
    account_type = models.CharField(max_length=2, choices=ACCOUNT_CHOICES)
    balance = models.DecimalField(max_digits=20, decimal_places=2)
    name = models.CharField(max_length=64)
    
    def __unicode__(self):
        return self.number.__str__() + " - owner " + self.user.get_full_name()

class Payment(models.Model):
    from_account = models.ForeignKey(Account, related_name='from_account')
    to_account = models.ForeignKey(Account, related_name='to_account')
    amount = models.DecimalField(validators=[positiveOrZero], max_digits=20, decimal_places=2)
    reference_number = models.BigIntegerField(blank=True, null=True)
    expiration_date = models.DateField(auto_now=True)
    message = models.CharField(max_length=160, blank=True, null=True)
    
    def save(self, force_insert=False, force_update=False, using=None):
        self.from_account.balance -= self.amount;
        self.to_account.balance += self.amount;
        self.from_account.save()
        self.to_account.save()
        models.Model.save(self, force_insert=force_insert, force_update=force_update, using=using)
    
class Card(models.Model):
    net_payment = models.BooleanField()
    credit_card = models.BooleanField()
    account = models.ForeignKey(Account)
    name = models.CharField(max_length=64)
